package org.free.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.free.client.GreetingService;
import org.free.data.Tags;
import org.free.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.Date;
import java.util.Iterator;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

/**
 * The server side implementation of login.
 */
@SuppressWarnings("serial")
public class SearchResult extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Key key = (Key) req.getSession().getAttribute("userid");
		
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();

		// The Query interface assembles a query

		String searchString = req.getParameter("term");
		String addTag = req.getParameter("addTag");
		if (addTag != null) {
			if(addTag.contains(",")){
				String tags[]=addTag.split(",");
				for (String string : tags) {
					Tags.setTag(key, string);
				}
			}else{
				Tags.setTag(key, addTag);
			}
			return;
		}
		Query q = new Query("Tag");
		// q.addFilter("tag", Query.FilterOperator.GREATER_THAN_OR_EQUAL,		 searchString);
		PreparedQuery pq = datastore.prepare(q);

		StringBuffer st = new StringBuffer();
		st.append("[");
		for (Entity result : pq.asIterable()) {

			String tagName = (String) result.getProperty("tag");
			if (tagName.toLowerCase().contains(searchString.toLowerCase()))
				st.append("\"" + tagName + "\"" + ",");

			// String lastName = (String) result.getProperty("lastName");
			// Long height = (Long) result.getProperty("height");
			// System.out.println(lastName + " " + firstName + ", " +
			// height.toString() + " inches tall");
		}

		resp.getOutputStream().println(
				st.toString().substring(0, st.toString().length() - 1) + "]");

	}

}
